package com.dst;

import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;

import java.util.Scanner;

public class CodeGenerator {
  public static void main(String[] args) {
    // 代码生成器
    AutoGenerator mpg = new AutoGenerator();

    // 数据源配置
    DataSourceConfig dsc = new DataSourceConfig();
    dsc.setUrl("jdbc:mysql://localhost:3306/auction_record?useUnicode=true&characterEncoding=utf-8");
    // dsc.setSchemaName("public");
    dsc.setDriverName("com.mysql.jdbc.Driver");
    dsc.setUsername("root");
    dsc.setPassword("123456");
    mpg.setDataSource(dsc);

    // 全局配置
    GlobalConfig gc = new GlobalConfig();
    String projectPath = System.getProperty("user.dir");
    gc.setOutputDir(projectPath + "/src/main/java");
    gc.setAuthor("董胜涛");
    gc.setOpen(false);//是否在代码生成后自动打开目录
//        gc.setServiceName("%sService");//去除service接口前的I
    mpg.setGlobalConfig(gc);

    // 包配置
    PackageConfig pc = new PackageConfig();
    pc.setParent("com.dst");
    pc.setEntity("entity");
    pc.setMapper("dao");
    pc.setService("service");
    pc.setServiceImpl("service.impl");
    pc.setController("controller");
    mpg.setPackageInfo(pc);

    // 生成策略配置
    StrategyConfig sc = new StrategyConfig();
    sc.setInclude(scanner("表名，多个英文逗号分割").split(","));//哪些表进行自动生成,需要用户输入
    sc.setEntityLombokModel(true);
    sc.setNaming(NamingStrategy.underline_to_camel);//数据库表映射到实体的命名策略
    sc.setColumnNaming(NamingStrategy.underline_to_camel);//数据库表字段映射到实体的命名策略
    sc.setRestControllerStyle(true);//设置RestController
    sc.setTablePrefix("t_"); //设置表的前缀，比如t_person的前缀是t_
    mpg.setStrategy(sc);

    mpg.execute();//开始生成

  }

  /**
   * <p>
   * 读取控制台内容
   * </p>
   */
  public static String scanner(String tip) {
    Scanner scanner = new Scanner(System.in);
    StringBuilder help = new StringBuilder();
    help.append("请输入" + tip + "：");
    System.out.println(help.toString());
    if (scanner.hasNext()) {
      String ipt = scanner.next();
      //MybatisPlus提供的工具类，做非空判断
      if (StringUtils.isNotEmpty(ipt)) {
        return ipt;
      }
    }
    throw new MybatisPlusException("请输入正确的" + tip + "！");
  }
}
